package com.qqserver.service;

import com.qqcommon.Message;
import com.qqcommon.MessageType;
import com.utils.Utility;

import java.io.IOException;
import java.io.ObjectOutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;

/**
 * 推送新闻的线程
 */
public class SendNewsToAllService implements  Runnable{
    @Override
    public void run() {

        //为了可以多次推送,用while
        while(true) {
            System.out.println("请输入服务器要推送的新闻/消息[输入exit退出推送]:");
            String news = Utility.readString(100);
            if(news.equals("exit")){
                break;
            }
            //创建消息
            Message message = new Message();
            message.setMesType(MessageType.MESSAGE_TO_ALL_MES);//群发
            message.setContent(news);
            message.setSender("服务器");
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd   hh:mm");
            message.setSend_time(sdf.format(new Date()));

            System.out.println("服务器推送了一条消息:"+news);

            //发送消息
            HashMap<String, ServerConnectClientThread> hm = ManageServerConnectClientThread.getHm();
            Iterator<String> iterator = hm.keySet().iterator();
            //遍历集合,取出对应的对象输出流
            while (iterator.hasNext()) {
                try {
                    ObjectOutputStream oos = new ObjectOutputStream(ManageServerConnectClientThread.getServerConnectClientThread(iterator.next()).getSocket().getOutputStream());
                    oos.writeObject(message);

                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }
}
